package com.micro.turtle.runner;

import cn.hutool.core.io.IoUtil;
import cn.hutool.setting.yaml.YamlUtil;
import com.micro.turtle.GitLab;
import com.micro.turtle.anon.CmdRunner;
import com.micro.turtle.constant.Cmd;
import com.micro.turtle.constant.Token;
import com.micro.turtle.constant.Url;
import com.micro.turtle.model.Conf;
import com.micro.turtle.util.Log;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 配置脚本
 *
 * @author jason.lv
 * @since 2022/1/20 16:23
 */
@CmdRunner
public class ConfRunner extends Runner {

    public ConfRunner() {
        super(Cmd.CONF);
    }

    @Override
    void exec() {
        // /Users/user/Desktop/Configs/gitlab.yml
        Log.info("默认配置:");
        // 读取配置
        print(load());
        String next = scannerNext("是否覆盖默认配置: y/n");
        switch (next) {
            case "y":
                next = scannerNext("输入配置文件路径:");
                print(Objects.requireNonNull(load(next)));
                break;
            case "n":
                break;
            default:
        }
    }

    public static void print(Conf prop) {
        try {
            Log.info("Conf >>>>> %s", prop.getFile());
            Field[] fields = prop.getClass().getDeclaredFields();
            for (Field field : fields) {
                Method method = prop.getClass().getMethod("get" + getMethodName(field.getName()));
                Object result = method.invoke(prop);
                Log.info("Conf >>>>> --%s: %s", field.getName(), result);
            }
        } catch (Exception e) {
            Log.info(e.getMessage());
        }
    }

    public static Conf load() {
        // read gitlab.yml conf
        InputStream is = GitLab.class.getClassLoader().getResourceAsStream("gitlab.yml");
        Conf conf = read(is);
        conf.setFile("gitlab.yml");
        return conf;
    }

    public static Conf load(String path) {
        File file = new File(path);
        if (!file.exists()) {
            Log.info("Conf >>>>> File not exist: %s", path);
            return new Conf();
        }
        Conf conf = read(IoUtil.toStream(file));
        conf.setFile(path);
        return conf;
    }

    private static Conf read(InputStream is) {
        // read gitlab.yml conf
        Conf conf = YamlUtil.load(is, Conf.class);
        Url.DOMAIN = conf.getDomain();
        Url.API = conf.getApi();
        Token.ACCESS_TOKEN = conf.getAccessToken();
        Token.GROUPS = conf.getIncludeGroup();
        return conf;
    }

    /**
     * 把一个字符串的第一个字母大写、效率是最高的、
     */
    private static String getMethodName(String fildeName) {
        byte[] items = fildeName.getBytes();
        items[0] = (byte) ((char) items[0] - 'a' + 'A');
        return new String(items);
    }
}
